'use strict';
const Controller = require('egg').Controller;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class DeliveryController extends Controller {

  async create() {
    const ctx = this.ctx;
    const params = ctx.request.body;
    console.log(params);
    const data = await ctx.model.Delivery.create(params);
    ctx.body = {
      code: 0,
      data,
      message: '创建成功',
    };
  }

  async index() {
    const { ctx } = this;
    const { did, name, contact, company, pageSize = 10, current = 1 } = ctx.query;
    const limit = Number(pageSize);
    const offset = limit * ((current || 1) - 1);
    const query = {};
    if (did) { query.where = { ...query.where, did }; }
    if (name) { query.where = { ...query.where, name }; }
    if (contact) { query.where = { ...query.where, contact }; }
    if (company) { query.where = { ...query.where, company }; }
    const data = await ctx.model.Delivery.findAll({ ...query, limit, offset });
    const totalData = await ctx.model.Delivery.findAndCountAll();
    ctx.body = {
      code: 0,
      data,
      pageInfo: {
        total: totalData.count,
        current,
        pageSize: Number(pageSize),
      },
      message: 'success',
    };
  }

  async show() {
    const { ctx } = this;
    const detail = await ctx.model.Delivery.findByPk(ctx.params.id, { raw: true });
    ctx.body = {
      code: 0,
      message: 'success',
      data: detail,
    };
  }

  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const delivery = await ctx.model.Delivery.findByPk(id);
    if (!delivery) {
      ctx.body = {
        code: 1,
        data: [],
        message: '不存在的快递',
      };
      return;
    }
    const params = ctx.request.body;
    const data = await delivery.update(params);
    ctx.body = {
      code: 0,
      data,
      message: '更新成功',
    };
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const delivery = await ctx.model.Delivery.findByPk(id);
    if (!delivery) {
      ctx.body = {
        code: 1,
        data: [],
        message: '不存在的产品',
      };
      return;
    }

    await delivery.destroy();
    ctx.body = {
      code: 0,
      message: '删除成功',
    };
  }
}

module.exports = DeliveryController;
